package com.song.NacosServiceRegistry;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.song.Utils.NacosUtil;
import com.song.enumeration.RpcError;
import com.song.exception.RpcException;
import com.song.transport.RPCRequest;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;

@Slf4j(topic = "c.NacosServiceRegistryImpl")
@Getter
@Setter
public class NacosNacosServiceRegistryImpl implements NacosServiceRegistry {
    //private static final String SERVER_ADDR = "10.1.124.24:8848";//Nacos host:port  通过Nacos启动cmd上面信息的网址进入网站 获取host（PS：不是127.0.0.1）
    //private static final NamingService namingService;//com.alibaba.nacos.api.naming.NamingService;
    private volatile LoadBalancer loadBalancer;

    public NacosNacosServiceRegistryImpl() {}

    //此处的负载均衡策略也可以在创建客户端时指定 对应的策略
    public NacosNacosServiceRegistryImpl(LoadBalancer loadBalancer) {
        if(loadBalancer == null) {
            this.loadBalancer = new RandomLoadBalancer();//默认随机
        } else {
            this.loadBalancer = loadBalancer;
        }
    }

    @Override
    public void register(String serviceName, InetSocketAddress inetSocketAddress) {//HelloService   127.0.0.1:port
        NacosUtil.registerService(serviceName, inetSocketAddress);
    }

    //通过
    @Override
    public InetSocketAddress lookupService(String serviceName, RPCRequest rpcRequest) {//从 Nacos 获取到的是所有提供这个服务的服务端 信息列表
        try {
            //获取某个服务的所有提供者列表
            List<Instance> instances = NacosUtil.getAllInstance(serviceName);
            if(instances.size() == 0) {
                log.error("找不到对应的服务：" + serviceName);
                throw new RpcException(RpcError.SERVICE_NOT_FOUND);
            }

            //负载均衡 选择提供这个服务的 服务器
            Instance instance = loadBalancer.select(instances, rpcRequest);
            return new InetSocketAddress(instance.getIp(), instance.getPort());
        } catch (NacosException e) {
            log.error("获取服务时发生错误：", e);
        }
        return null;
    }
}
